package demo.database.MariaDB.D02_性能测试;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.concurrent.CountDownLatch;

import com.titan.core.utils.common.interfaces.ICall;
import com.titan.core.utils.data.AssertUtils;
import com.titan.core.utils.db.DBUtils;
import com.titan.core.utils.db.JdbcUtils;
import com.titan.core.utils.dbinfo.dialect.DBDialect;
import com.titan.core.utils.dbinfo.dialect.IDBDialect;
import com.titan.core.utils.debug.Timer;
import com.titan.core.utils.io.ConsoleUtils;
import com.titan.core.web.options.RunMainOption;
import com.titan.core.web.utils.SpringBootUtils;
import com.titan.services.ddm.v2.TemplateEngine.S0003M1104.S0003M1104Factory;

import demo.database.MariaDB.utils.MariaDBUtils;


public class T02_写入性能测试 implements ICall {
    public static final String TABLE_NAME = "cc";
    
    public void call() throws Exception {
        Timer timer = Timer.$();
//        run(1);         // [测试用时] [415毫秒] [用时(ms)=415]
//        run(10);        // [测试用时] [569毫秒] [用时(ms)=569]
//        run(100);       // [测试用时] [404毫秒] [用时(ms)=404]
//        run(1000);      // [测试用时] [863毫秒] [用时(ms)=863]
//        run(10000);     // [测试用时] [3秒 756毫秒] [用时(ms)=3756]
//        run(100000);    // [测试用时] [19秒 380毫秒] [用时(ms)=19380]
        timer.print("测试用时");
        EXIT.countDown();
    }
    private static void run(int count) throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = MariaDBUtils.getConnection();
            DBUtils.execute(conn, "DROP TABLE IF EXISTS `"+TABLE_NAME+"`");
            DBUtils.execute(conn, "CREATE TABLE `"+TABLE_NAME+"` (`id` varchar(40) PRIMARY KEY, `data` int, `create_dt` datetime)");
            
            stmt = conn.prepareStatement("INSERT INTO `"+TABLE_NAME+"` VALUES (UUID(), ?, NOW())");
            for(int i = 0; i < count; i++){
                stmt.setInt(1, i);
                stmt.execute();
            }
            
            String value = DBUtils.getValue(conn, "select count(*) from `"+TABLE_NAME+"`");
            AssertUtils.assertEquals(Integer.toString(count), value, false);
        } finally {
            DBUtils.close(stmt);
            DBUtils.close(conn);
        }
    }    


    public static void main(String[] args) throws InterruptedException {
        RunMainOption option = RunMainOption.$().addStartupArgs(
                "--titan.mode=development"   // # development configuration production test
              , "--titan.log.DateFile.enabled=false"
              , "--titan.node.home=E:\\HDJT"
        );
        SpringBootUtils.runMain(option, new T02_写入性能测试(), EXIT, EXIT_TIMEOUT_SECONDS);
    }
    private static final CountDownLatch EXIT = new CountDownLatch(1);
    private static final int EXIT_TIMEOUT_SECONDS = 3;
}
